package Core;

import java.io.OutputStream;
import java.util.Vector;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Mr Bao
 */
public class WriterThread implements Runnable {

    private boolean isRunning = true;
    private Vector queue;
    private OutputStream out;
    private long delayTime = 10L;
    private String message;

    public WriterThread(OutputStream out) {
        this.out = out;
        queue = new Vector();
        new Thread(this).start();
    }

    public void FlushOutputQueue() {
        while (queue.size() > 0) {
            message = (String) queue.elementAt(0);
            queue.removeElementAt(0);
//            byte[] outMsg = null;
//            try {
//                byte[] msgUTF8 = message.getBytes("UTF-8");
//                outMsg = new byte[msgUTF8.length + 1];
//                for (int j = 0; j < msgUTF8.length; j++) {
//                    outMsg[j] = msgUTF8[j];
//                }
//                outMsg[outMsg.length - 1] = (byte) 3;
//            } catch (Exception e) {
//            }
//            if (outMsg != null) {
//                try {
//                    out.write(outMsg);
//                    out.flush();
//                } catch (Exception e) {
//                }
//            }
            try {
                out.write(message.getBytes());
            } catch (Exception e) {
            }
        }
    }

    public synchronized void QueueMessage(String message) {
        System.out.println(message);
        queue.addElement(message);
        notify();
    }

    public void Halt() {
        isRunning = false;
    }

    public synchronized void run() {
        int gcTimer = 0;
        try {
            while (isRunning) {
                gcTimer++;
                FlushOutputQueue();
                wait(delayTime);
                if (gcTimer == 1000) {
                    Runtime.getRuntime().gc();
                    gcTimer = 0;
                }
            }
        } catch (Exception e) {
        }
    }
}
